const express = require('express');
const expressWs = require('express-ws')

const {pushMessage} = require("../socket-server/module/doc/index")

const { handleResponse,connectSuccResponse } = require("../socket-server/common/index")
const app = express();

//利用expressWs中间件包装app项目
const wsClients = []
expressWs(app);
app.wsCients = wsClients

//引如swagger文档及配置
const expressSwagger = require('express-swagger-generator')(app)
const { options } = require("../socket-server/common/config.js")
expressSwagger(options)

app.ws("/message",(ws,req)=>{
  const succRes = connectSuccResponse()
  ws.send(succRes)
  ws.on('message', function (params) {
      const res = handleResponse(params)
      //鉴于只做调试功能，所以只允许单点socket推送
      if(wsClients.length < 1){
        wsClients.push(ws)
      }
      ws.send(res)
      
  })
  ws.on("close",function(e){
    wsClients.length = 0
    console.log("close connection")
  })
})

app.post("/message/pushMessage",(req,res)=>{
  pushMessage(req,res)
  //将广播记录的所有用于做统一推送
  wsClients.forEach(client=>{
    const params = JSON.stringify(req.query)
    client.send(handleResponse(params));
  })
})

app.listen(8086,()=>{
  console.log(" test pushMessageApi in http://localhost:8086/swagger ")
});

